//
//  EmoticonKeyboardView.swift
//  EmoticonKeyboard
//
//  Created by liii on 16/8/14.
//  Copyright © 2016年 liii. All rights reserved.
//

import UIKit
import SnapKit

private let EmoticonCellId = "EmoticonCellId"

class EmoticonKeyboardView: UIView {
    
    // 获取模型数组
    var packages = EmoticonManager.sharedEmotionManager.packages

    override init(frame: CGRect) {
        let rect = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 226)
        super.init(frame: rect)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 等待自动布局系统根据约束修改完collectionView的试图大小之后，再设置itemSize
        let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = collectionView.bounds.size
    }
    
    private func setupUI() {

        addSubview(toolBar)
        addSubview(collectionView)
        addSubview(pageControl)
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self)
            make.height.equalTo(36)
        }
        collectionView.snp_makeConstraints { (make) -> Void in
            make.left.right.top.equalTo(self)
            make.bottom.equalTo(toolBar.snp_top)
        }
        pageControl.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.bottom.equalTo(collectionView)
        }
        
        // 给闭包赋值，实现 toolBar 和 collectionView 的联动
        toolBar.emoticonDidClick = {(index: Int) -> () in
            // 点击工具条按钮后，让collectionView滚动到对应组
            let indexPath = NSIndexPath(forItem: 0, inSection: index)
            self.collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: true)
            
            // 更新pageControl
            self.updatePageControlData(indexPath)
        }
        
        // 首次显示pageControl, 设置默认值
        updatePageControlData(NSIndexPath(forItem: 0, inSection: 0))
        
    }
    
    // 工具条
    private lazy var toolBar: EmoticonToolbar = EmoticonToolbar()
    
    // 分页
    private lazy var pageControl: UIPageControl = {
        
        let pc = UIPageControl()
        pc.numberOfPages = 5
        pc.currentPage = 0
        
        pc.pageIndicatorTintColor = UIColor.whiteColor()
        pc.currentPageIndicatorTintColor = UIColor.redColor()
        
        // 用KVC, 给pageControl的私有属性, 设置图片
        pc.setValue(UIImage(named: "compose_keyboard_dot_normal"), forKey: "_pageImage")
        pc.setValue(UIImage(named: "compose_keyboard_dot_selected"), forKey: "_currentPageImage")
        
        return pc
    }()
    
    // 表情
    private lazy var collectionView: UICollectionView = {
        
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .Horizontal
        
        let cv = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
        cv.delegate = self
        cv.dataSource = self
        cv.pagingEnabled = true
        cv.showsHorizontalScrollIndicator = false
        
        // 注册Cell
        cv.registerClass(EmoticonCell.self, forCellWithReuseIdentifier: EmoticonCellId)
        
        return cv
    }()
}

// UICollectionViewDataSource, UICollectionViewDelegate
extension EmoticonKeyboardView: UICollectionViewDataSource, UICollectionViewDelegate {

    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return packages[section].sectionEmoticon.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(EmoticonCellId, forIndexPath: indexPath) as! EmoticonCell
        
        // 传递模型数据
        cell.emoticons = packages[indexPath.section].sectionEmoticon[indexPath.item]
        
        return cell
    }
    
//    // 滚动结束的时候调用
//    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
//    
//        let cv = scrollView as! UICollectionView
//        // 获取最后显示的Cell
//        if let cell = cv.visibleCells().first {
//            // 根据cell获取indexPath
//            let indexPath = cv.indexPathForCell(cell)
//            
//            // 让按钮滚动
//            toolBar.changeButton?(index: indexPath?.section ?? 0)
//            // 更新pageControl
//            updatePageControlData(indexPath!)
//        }
//    }
    
    // 滚动的过程中调用
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        // 获取当前Cell的下一个Cell的中心点(第一个Cell的中心点 + 偏移量)
        var nextCellCenter = scrollView.center
        nextCellCenter.x += scrollView.contentOffset.x
        // 获取滚动过程中所有可见Cell的indexPath
        let indexPaths = collectionView.indexPathsForVisibleItems()
        // 根据indexPath获取到所有可见的Cell
        for indexPath in indexPaths {
            let cell = collectionView.cellForItemAtIndexPath(indexPath)!
            // 监测Cell是否滚动到了第二个Cell的中心点
            if cell.frame.contains(nextCellCenter) {
                // 滚动到了就更新pageControl的currentPage等于当前页的indexPath
                updatePageControlData(indexPath)
            }
        }
    }
    
    // 设置pageControl
    private func updatePageControlData(indexPath: NSIndexPath) {
        pageControl.numberOfPages = EmoticonManager.sharedEmotionManager.packages[indexPath.section].sectionEmoticon.count
        pageControl.currentPage = indexPath.item
    }
    
}

